package com.bootdo.system.controller;

import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import org.apache.commons.lang3.StringUtils;
import org.apache.http.client.ClientProtocolException;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.ui.Model;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.client.RestTemplate;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import com.bootdo.app.service.WXService;
import com.bootdo.common.config.BootdoConfig;
import com.bootdo.common.utils.EmojiConverterUtil;
import com.bootdo.common.utils.GetUserList;
import com.bootdo.common.utils.HttpUtil;
import com.bootdo.common.utils.R;
import com.bootdo.common.utils.RestTemplateUtil;
import com.bootdo.common.utils.ShiroUtils;
import com.bootdo.common.utils.xstream;
import com.bootdo.common.wx.WeiXinUtil;
import com.bootdo.system.domain.Articles;
import com.bootdo.system.domain.Media_id;
import com.bootdo.system.domain.News;
import com.bootdo.system.domain.RoleDO;
import com.bootdo.system.domain.SendPojo;
import com.bootdo.system.domain.TbScgl;
import com.bootdo.system.domain.TbSpjc;
import com.bootdo.system.domain.TbWallet;
import com.bootdo.system.domain.TbWeixinconfig;
import com.bootdo.system.domain.TbWxmenu;
import com.bootdo.system.domain.TbWxuser;
import com.bootdo.system.domain.UserDO;
import com.bootdo.system.service.RoleService;
import com.bootdo.system.service.ScglService;
import com.bootdo.system.service.SpjcService;
import com.bootdo.system.service.UserService;
import com.bootdo.system.service.WalletService;
import com.bootdo.system.service.WxConfigService;
import com.bootdo.system.service.WxMenuService;
import com.bootdo.system.service.WxUserService;

@RequestMapping("/config")
@Controller
public class ConfigController {
	
	@Autowired
	private WxConfigService wxConfigService;
	
	@Autowired
	private WalletService walletService;
	
	@Autowired
	private WxMenuService wxMenuService;
	
	@Autowired
	private WxUserService wxUserService;
	
	@Autowired
	private UserService userService;
	
	@Autowired
	private SpjcService spjcService;
	
	@Autowired
	RoleService roleService;
	@Autowired
	ScglService scglService;
	
	@Autowired
	private WXService wXService;
	
	@Autowired
	private BootdoConfig bootdoConfig;
	
	String prefix = "system/config";
	
	
	@GetMapping("wx")
	String task() {
		return prefix + "/wxConfig";
	}
	
	@GetMapping("qbsz")
	String wdrw() {
		return prefix + "/qbConfig";
	}
	
	@GetMapping("gzh")
	String wdsh() {
		return prefix + "/gzhConfig";
	}
	

	@GetMapping("user")
	String user() {
		return prefix + "/user";
	}
	
	
	
	@ResponseBody
	@RequestMapping("/gzhConfig/list")
	public List<TbWxmenu> gzhConfigList() {
		UserDO user = ShiroUtils.getUser();
		if(user.getUserId() != 1L) {
			List<RoleDO> list2 = roleService.getRoleByUserId(user.getUserId());
			boolean falg=false;
			for (RoleDO role : list2) {
				if(role.getRoleId() == 59L) {
					falg=true;
				}
			}
			if(falg) {//公司数据权限
				List<Long> idByDeptId = userService.getIdByDeptId(user.getDeptId());
				return wxMenuService.list(null, idByDeptId);
			}else {
				return wxMenuService.list(user.getUserId(), null);
			}
		}
		return wxMenuService.list(null, null);
	}
	
	@ResponseBody
	@RequestMapping("/gzhConfig/gzhSendMsgList")
	public List<TbScgl> gzhSendMsgList(Integer gzhId) {
		return scglService.list(gzhId,0);
	}
	
	@ResponseBody
	@RequestMapping("/gzhConfig/gzhSendMsgList2")
	public List<TbScgl> gzhSendMsgList2(Integer gzhId) {
		return scglService.list(gzhId,1);
	}
	
	@ResponseBody
	@RequestMapping("/qbConfig/list")
	public List<TbWallet> getWall() {
		List<TbWallet> list=new ArrayList<TbWallet>();
		TbWallet wall = walletService.getWall();
		if(wall != null) {
			list.add(wall);
		}
		return list;
	}
	
	@ResponseBody
	@RequestMapping("/wxConfig/list")
	public List<TbWeixinconfig> searchWjList() {
		UserDO user = ShiroUtils.getUser();
		if(user.getUserId() != 1L) {
			List<RoleDO> list2 = roleService.getRoleByUserId(user.getUserId());
			boolean falg=false;
			for (RoleDO role : list2) {
				if(role.getRoleId() == 59L) {
					falg=true;
				}
			}
			if(falg) {//公司数据权限
				List<Long> idByDeptId = userService.getIdByDeptId(user.getDeptId());
				List<Integer> us=new ArrayList<Integer>();
				for (Long long1 : idByDeptId) {
					int intValue = long1.intValue();
					us.add(intValue);
				}
				return wxConfigService.list(null, us);
			}else {
				return wxConfigService.list(user.getUserId().intValue(), null);
			}
		}
		return wxConfigService.list(null,null);
	}
	
	
	@GetMapping("/qbConfig/qbEdit/{id}")
	String edit(Model model,@PathVariable("id") Integer id) {
		TbWallet wallet = walletService.getById(id);
		model.addAttribute("qb", wallet);
		return prefix+"/qbEdit";
	}
	
	
	@PostMapping("/qbConfig/qbUpdate")
	@ResponseBody
	R update(TbWallet table) {
		if (walletService.insert2update(table) > 0) {
			return R.ok();
		}
		return R.error();
	}
	
	
	@GetMapping("/wxConfig/wxEdit/{id}")
	String wxEdit(Model model,@PathVariable("id") Integer id) {
		TbWeixinconfig wx = wxConfigService.getById(id);
		model.addAttribute("wx", wx);
		return prefix+"/wxEdit";
	}
	
	@GetMapping("/wxConfig/spjcEdit/{id}")
	String spjcEdit(Model model,@PathVariable("id") Integer id) {
		TbWeixinconfig wx = wxConfigService.getById(id);
		TbSpjc spjc = spjcService.getBySid(wx.getId());
		model.addAttribute("wx", wx);
		model.addAttribute("spjc", spjc);
		return prefix+"/spjcEdit";
	}
	
	@GetMapping("/gzhConfig/msgAdd/{id}")
	String msgAdd(Model model,@PathVariable("id") Integer id) {
		model.addAttribute("gzhId", id);
		return prefix+"/msgAdd";
	}
	
	@GetMapping("/gzhConfig/msgAdd2/{id}")
	String msgAdd2(Model model,@PathVariable("id") Integer id) {
		model.addAttribute("gzhId", id);
		return prefix+"/msgAdd2";
	}
	
	
	@GetMapping("/gzhConfig/msgEdit/{id}")
	String msgEdit(Model model,@PathVariable("id") Integer id) {
		TbScgl byId = scglService.getById(id);
		model.addAttribute("scgl", byId);
		return prefix+"/msgEdit";
	}
	
	@GetMapping("/gzhConfig/msgEdit2/{id}")
	String msgEdit2(Model model,@PathVariable("id") Integer id) {
		TbScgl byId = scglService.getById(id);
		model.addAttribute("scgl", byId);
		return prefix+"/msgEdit2";
	}
	
	@GetMapping("/wxConfig/wxAdd")
	String wxAdd(Model model) {
		return prefix+"/wxAdd";
	}
	
	@GetMapping("/gzhConfig/gzhAdd")
	String gzhAdd(Model model) {
		return prefix+"/gzhAdd";
	}
	
	
	@PostMapping("/wxConfig/wxUpdate")
	@ResponseBody
	R wxUpdate(TbWeixinconfig table) {
		if (wxConfigService.insert2update(table) > 0) {
			return R.ok();
		}
		return R.error();
	}
	
	@PostMapping("/gzhConfig/msgUpdate")
	@ResponseBody
	R msgUpdate(TbScgl table) throws ClientProtocolException, IOException {
		//Integer gzhId = table.getGzhId();
		//		TbWxmenu byId = wxMenuService.getById(gzhId);
//		String accessToken =WeiXinUtil.getOauth2AccessToken2(byId.getAppid(), byId.getAppsecret());
//		String addNews = addNews(table,accessToken);
//		HashMap hashMap = JSON.parseObject(addNews, HashMap.class);
//		String media_id = (String) hashMap.get("media_id");
//		table.setMediaId(media_id);
		System.out.println(table.getScms());
		String emojiConvert1 = EmojiConverterUtil.emojiConvert1(table.getScms());
		table.setScms(emojiConvert1);
		if (scglService.insert2update(table) > 0) {
				return R.ok();
		}
		return R.error();
	}
	
	@PostMapping("/gzhConfig/spjcUpdate")
	@ResponseBody
	R spjcUpdate(TbSpjc table) throws ClientProtocolException, IOException {
		if (spjcService.insert2update(table) > 0) {
				return R.ok();
		}
		return R.error();
	}
	
//	@PostMapping("/gzhConfig/msgUpdate2")
//	@ResponseBody
//	R msgUpdate2(TbScgl table) throws ClientProtocolException, IOException {
//		Integer gzhId = table.getGzhId();
//		TbWxmenu byId = wxMenuService.getById(gzhId);
//		String accessToken =WeiXinUtil.getOauth2AccessToken2(byId.getAppid(), byId.getAppsecret());
//		String addNews = addNews(table,accessToken);
//		HashMap hashMap = JSON.parseObject(addNews, HashMap.class);
//		String media_id = (String) hashMap.get("media_id");
//		table.setMediaId(media_id);
//		if (scglService.insert2update(table) > 0) {
//				return R.ok();
//		}
//		return R.error();
//	}
	
	@PostMapping("/gzhConfig/msgDoSend")
	@ResponseBody
	R msgDoSend(Integer id,Integer gzhId) throws ClientProtocolException, IOException {
		TbWxmenu byId = wxMenuService.getById(gzhId);
    	TbWeixinconfig selectByUserId2 = wxConfigService.selectByUserId(byId.getAdminId().intValue());
		String accessToken =WeiXinUtil.getOauth2AccessToken2(byId.getAppid(), byId.getAppsecret());
		TbScgl byId2 = scglService.getById(id);
		Integer sclb = byId2.getSclb();
		List<String> userList =GetUserList.getUserList(accessToken);
//		sendMsg(accessToken,byId2.getMediaId());
		if(sclb == 0) {
			for (String string : userList) {
				sendMsg2(accessToken, string,byId2.getTitile(),byId2.getAppUrl(),selectByUserId2.getAppid(), byId2.getCode());
			}
		}else if(sclb == 1) {
			for (String string : userList) {
				sendMsg3(accessToken, string, byId2.getTitile(), byId2.getScms(), bootdoConfig.getSsl()+byId2.getUrl(), byId2.getYmlj());
			}
		}else if(sclb == 2) {
			for (String string : userList) {
				sendMsg4(accessToken, string, byId2.getScms());
			}
		}
		return R.ok();
	}
	
//	@PostMapping("/gzhConfig/msgDoSend")
//	@ResponseBody
//	R msgDoSend(String mediaId,Integer gzhId) throws ClientProtocolException, IOException {
//		TbWxmenu byId = wxMenuService.getById(gzhId);
//		String accessToken =WeiXinUtil.getOauth2AccessToken2(byId.getAppid(), byId.getAppsecret());
//		String msg = sendMsg(accessToken,mediaId);
//		return R.ok();
//	}
//	
	
	private  Articles createArticles(TbScgl table){
	    Articles articles = new Articles();
	    List<News> dataList = new ArrayList<News>();
	    News  news1 = new News();
	    news1.setTitle(table.getTitile());
	    news1.setThumb_media_id(table.getCode());
	    news1.setAuthor("");
	    news1.setShow_cover_pic(1);//显示封面
	    news1.setContent(table.getScms());
	    news1.setContent_source_url("https://www.baidu.com/");  //图文消息的原文地址，即点击“阅读原文”后的URL
	    dataList.add(news1);
	    articles.setArticles(dataList);
	    return articles;

	}
	
	/**
	 *新增永久图文素材
	 * @throws IOException 
	 * @throws ClientProtocolException 
	 */
	public  String addNews(TbScgl table,String accessToken) throws ClientProtocolException, IOException {
        RestTemplate restTemplate = RestTemplateUtil.getInstance("utf-8");
	    Articles articles = createArticles(table);
	    if (accessToken != null) {
	        String url = "https://api.weixin.qq.com/cgi-bin/material/add_news?access_token="+accessToken;
	        //将菜单对象转换成JSON字符串
	        String jsonNews = JSONObject.toJSONString(articles);
	        //发起POST请求创建菜单
	        String jsonObject = restTemplate.postForObject(url, jsonNews,String.class);
	        System.out.println(jsonObject);
	        return jsonObject;
	    }
	    return null;
	}
	
	private void sendMsg2(String accessToken,String openId,String title,String appUrl,String appid,String thumb_media_id){
		if(appUrl == null) {
			appUrl="pages/index/index";
		}
		String strurl="https://api.weixin.qq.com/cgi-bin/message/custom/send?access_token="+accessToken;
        String responeJsonStr = "{";
        responeJsonStr += "\"touser\": \"" + openId + "\",";
        responeJsonStr += "\"msgtype\": \"miniprogrampage\",";
        responeJsonStr += "\"miniprogrampage\": {";
        responeJsonStr += "  \"title\": \"" + title + "\",";
        responeJsonStr += "  \"appid\": \"" + appid + "\",";
        responeJsonStr += "  \"pagepath\": \"" + appUrl + "\",";
        responeJsonStr += "  \"thumb_media_id\": \"" + thumb_media_id + "\"";
        responeJsonStr += "}";
        responeJsonStr += "}";
//		  System.out.println(responeJsonStr);
		  xstream.connectWeiXinInterface(strurl,responeJsonStr);
	}
	
	private void sendMsg3(String accessToken,String openId,String title,String description,String picurl,String url){
		 if(url == null) {
	        	url="";
	        }
		String strurl="https://api.weixin.qq.com/cgi-bin/message/custom/send?access_token="+accessToken;
        String responeJsonStr = "{";
        responeJsonStr += "\"touser\": \"" + openId + "\",";
        responeJsonStr += "\"msgtype\": \"news\",";
        responeJsonStr += "\"news\": {";
        responeJsonStr += "\"articles\": [{";
        responeJsonStr += "  \"title\": \"" + title + "\",";
        responeJsonStr +=	"  \"description\": \"" + description + "\",";
        responeJsonStr += "  \"url\": \"" + url + "\",";
        responeJsonStr += "  \"picurl\": \"" + picurl + "\",";
        responeJsonStr += "}]";
        responeJsonStr += "}";
        responeJsonStr += "}";
//		  System.out.println(responeJsonStr);
		  xstream.connectWeiXinInterface(strurl,responeJsonStr);
	}
	private void sendMsg4(String accessToken,String openId,String content){
        String strurl="https://api.weixin.qq.com/cgi-bin/message/custom/send?access_token="+accessToken;
        String responeJsonStr = "{";
        responeJsonStr += "\"touser\": \"" + openId + "\",";
        responeJsonStr += "\"msgtype\": \"text\",";
         responeJsonStr += "\"text\": {";
         responeJsonStr += "  \"content\": \"" + content + "\",";
         responeJsonStr += "}";
        responeJsonStr += "}";
//		  System.out.println(responeJsonStr);
		  xstream.connectWeiXinInterface(strurl,responeJsonStr);
	}
	
	
	public String sendMsg(String token,String id) throws ClientProtocolException, IOException {
		//先获取用户openid列表
		String url = "https://api.weixin.qq.com/cgi-bin/message/mass/send?access_token="+token;
		List userList =GetUserList.getUserList(token);
		String openid = userList.toString();
		System.out.println(openid);
		Media_id m = new Media_id();
		m.setMedia_id(id);
		JSONObject json1 = (JSONObject) JSONObject.toJSON(m);
		String str1 = json1.toString();
		System.out.println(str1);
		//封装请求参数
		SendPojo sp = new SendPojo();
		sp.setTouser(userList);
		sp.setMpnews(str1);
		sp.setMsgtype("mpnews");
		sp.setSend_ignore_reprint(0);
		JSONObject json = (JSONObject) JSONObject.toJSON(sp);
		String str = json.toString();
		str= str.replace("\\", "");  
		str= str.replace("\"{", "{");
		str= str.replace("}\"", "}");
		System.out.println(str);
		return HttpUtil.httpPost(url, null, str);
	}
	
	
	@PostMapping("/wxConfig/editWx2Sfzy")
	@ResponseBody
	R editWx2Sfzy(Integer id) {
		TbWeixinconfig byId = wxConfigService.getById(id);
		Integer sfzy = byId.getSfzy();
		if(sfzy == 0) {
			byId.setSfzy(1);
		}else {
			byId.setSfzy(0);
		}
		if (wxConfigService.insert2update(byId) > 0) {
			return R.ok();
		}
		return R.error();
	}
	
	@PostMapping("/wxConfig/removeWx")
	@ResponseBody
	R removeWx(Integer id) {
		if (wxConfigService.remove(id) > 0) {
			return R.ok();
		}
		return R.error();
	}

	@PostMapping("/wxConfig/batchRemoveWx")
	@ResponseBody
	R batchRemoveWx(@RequestParam("ids[]") Integer[] wxIds) {
		int r = wxConfigService.batchremove(wxIds);
		if (r > 0) {
			return R.ok();
		}
		return R.error();
	}
	
	
	@GetMapping("/gzhConfig/gzhEdit/{id}")
	String gzhEdit(Model model,@PathVariable("id") Integer id) {
		TbWxmenu gzh = wxMenuService.getById(id);
		model.addAttribute("gzh", gzh);
		return prefix+"/gzhEdit";
	}
	
	@GetMapping("/gzhConfig/gzhSendMsg/{id}")
	String gzhSendMsg(Model model,@PathVariable("id") Integer id) {
		model.addAttribute("gzhId", id);
		return prefix+"/gzhSendMsg";
	}
	
	@GetMapping("/gzhConfig/gzhSendMsg2/{id}")
	String gzhSendMsg2(Model model,@PathVariable("id") Integer id) {
		model.addAttribute("gzhId", id);
		return prefix+"/gzhSendMsg2";
	}
	
	@PostMapping("/gzhConfig/gzhUpdate")
	@ResponseBody
	R gzhUpdate(TbWxmenu table) {
		//设置公众号的还没有写----待定
		String replace = table.getSmalltext().replace("null,","").replace(",null","");
		table.setSmalltext(replace);
		System.out.println(table.getSmalltext());
		String replace2 = replace.replace("url2\"","url\"");
		System.out.println(replace2);
		HashMap hashMap = JSON.parseObject(replace, HashMap.class);
		/*List<Map<String,Object>> object = (List<Map<String, Object>>) hashMap.get("button");
		for (Map<String, Object> map : object) {
			String name = (String) map.get("name");
			if(!StringUtils.isNoneBlank(name)) {
				return R.error("一级菜单栏不可为空");
			}
			List<Map<String,Object>> subButtonList =(List<Map<String, Object>>) map.get("sub_button");
			for (Map<String, Object> map2 : subButtonList) {
				int size = map2.size();
				if(size > 5) {
					return R.error(map2.get("name")+"参数配置不正确");
				}else {
					String url2 = (String) map2.get("url2");
					String type = (String) map2.get("type");
					if(StringUtils.isNoneBlank(url2) && !"miniprogram".equals(type) ) {
						return R.error(map2.get("name")+"参数配置不正确，请再选中小程序尝试");
					}
				}
			}
		}*/
		Integer id = table.getId();
		TbWxmenu byId = wxMenuService.getById(id);
		boolean createWxMenu = wXService.createWxMenu(byId.getAppid(), byId.getAppsecret(), replace2);
		if(createWxMenu) {
			if (wxMenuService.insert2update(table) > 0) {
				return R.ok();
			}
		}
		return R.error("参数配置失败");
	}
	
	@PostMapping("/gzhConfig/gzhAdd")
	@ResponseBody
	R gzhAdd(TbWxmenu table) {
		table.setSmalltext("{\"button\":[{\"name\":\"样例1\",\"sub_button\":[{\"name\":\"样例1-1\",\"url\":\"https://www.baidu.com\",\"type\":\"view\"}]},{\"name\":\"样例2\",\"sub_button\":[{\"name\":\"样例2-1\",\"url\":\"https://www.baidu.com\",\"type\":\"view\"}]},{\"name\":\"样例3\",\"sub_button\":[{\"name\":\"样例3-1\",\"url\":\"https://www.baidu.com\",\"type\":\"view\"}]}]}");
		if (wxMenuService.insert2update(table) > 0) {
			return R.ok();
		}
		return R.error();
	}
	
	@PostMapping("/gzhConfig/gzhAdd2")
	@ResponseBody
	R gzhAdd2(TbWxmenu table) {
		if (wxMenuService.insert2update(table) > 0) {
			return R.ok();
		}
		return R.error();
	}
	
	
	@PostMapping("/gzhConfig/remove")
	@ResponseBody
	R removeGzh(Integer id) {
		if (wxMenuService.remove(id) > 0) {
			return R.ok();
		}
		return R.error();
	}

	@PostMapping("/gzhConfig/batchRemove")
	@ResponseBody
	R batchRemoveGzh(@RequestParam("ids[]") Integer[] gzhIds) {
		int r = wxMenuService.batchremove(gzhIds);
		if (r > 0) {
			return R.ok();
		}
		return R.error();
	}
	
	@PostMapping("/gzhConfig/batchRemoveMsg")
	@ResponseBody
	R batchRemoveMsg(@RequestParam("ids[]") Integer[] msgIds) {
		int r = scglService.batchremove(msgIds);
		if (r > 0) {
			return R.ok();
		}
		return R.error();
	}
	
	@PostMapping("/gzhConfig/dataSync")
	@ResponseBody
	R dataSync(Integer id) throws ClientProtocolException, IOException {
		TbWxmenu byId = wxMenuService.getById(id);
		String accessToken =WeiXinUtil.getOauth2AccessToken2(byId.getAppid(), byId.getAppsecret());
		List userList = GetUserList.getUserList(accessToken);
		List<TbWxuser> newList=new ArrayList<TbWxuser>();
		for (int i = 0; i < userList.size(); i++) {
			String openId = (String) userList.get(i);
			 String res = getUnioId(openId,accessToken);
		     HashMap hashMap = JSON.parseObject(res, HashMap.class);
		     String unioId = (String) hashMap.get("unionid");
		     TbWxuser table2 = JSON.parseObject(res, TbWxuser.class);
	    	 table2.setOpenid(null);
    		 table2.setSid(byId.getAdminId()+"");
    		 table2.setWxUnionId(unioId);
    		 table2.setWxuserId(0);
    		 table2.setGzhOpenId(openId);
    		 newList.add(table2);
		}
		
		int res =wxUserService.insertBatch(newList);
		if(res > 0) {
			return R.ok();
		}
		return R.error();
	}
	
	private String getUnioId(String openId,String token) {
		String aa="https://api.weixin.qq.com/cgi-bin/user/info?access_token="+token+"&openid="+openId+"&lang=zh_CN";
		String doGet = HttpUtil.doGet(aa, null);
		return doGet;
	}
	
}
